<template>
    <div class="user-manage">
        <!-- 搜索表单 -->
        <el-form :inline="true" :model="searchForm" class="search-form">
            <div class="item-group">
                <el-form-item label="募捐机构ID:">
                    <el-input v-model="searchForm.agencyId" placeholder="请输入募捐机构ID" />
                </el-form-item>
                <el-form-item label="募捐机构名称:">
                    <el-input v-model="searchForm.agencyName" placeholder="请输入募捐机构名称" />
                </el-form-item>
                <el-form-item label="募捐机构电话:">
                    <el-input v-model="searchForm.agencyPhone" placeholder="请输入募捐机构电话" />
                </el-form-item>
                <el-form-item label="募捐机构性质:">
                    <el-select v-model="searchForm.agencyNature" placeholder="请选择募捐机构性质" style="width: 170px;" clearable>
                        <el-option v-for="item in agencyNatureList" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="组织评级:">
                    <el-cascader v-model="searchForm.organizationRating" :options="ratingList" placeholder="请选择组织评级" clearable />
                </el-form-item>
                <el-form-item label="法人姓名:">
                    <el-input v-model="searchForm.corporateName" placeholder="请输入法人姓名" />
                </el-form-item>
                <el-form-item label="社会统一信用代码:">
                    <el-input v-model="searchForm.socialCreditCode" placeholder="请输入社会统一信用代码" />
                </el-form-item>
                <el-form-item label="登记证书类型:">
                    <el-select v-model="searchForm.registrationCertificateType" placeholder="请选择登记证书类型" style="width: 170px;" clearable>
                        <el-option v-for="item in registrationCertificateTypeList" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>
            </div>
            <div class="btn-group">
                <el-button type="primary" @click="getAgencyList" size="small">
                    <el-icon><Search /></el-icon>
                    搜索
                </el-button>
                <el-button type="success" @click="handleEdit(1)" size="small">
                    <el-icon><Plus /></el-icon>
                    新增
                </el-button>
                <el-button type="danger" @click="handleDelete('batch')" size="small">
                    <el-icon><Minus /></el-icon>
                    批量删除
                </el-button>
            </div>
        </el-form>
        <!-- 表格数据 -->
        <el-table 
            :data="tableData" 
            style="width: 100%" 
            border 
            :header-cell-style="{ background: 'rgb(216,231,246)' }" 
            max-height="500"
            @selection-change="handleSelectionChange"
        >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="agencyId" label="募捐机构ID" width="100" />
            <el-table-column prop="agencyName" label="募捐机构名称" width="150" />
            <el-table-column prop="agencyLogo" label="募捐机构logo" width="120">
                <template #default="scope">
                    <el-image :src="imageUrl + scope.row.agencyLogo" style="width: 50px; height: 50px" />
                </template>
            </el-table-column>
            <el-table-column prop="agencyEmail" label="募捐机构邮箱" width="150" />
            <el-table-column prop="agencyPhone" label="募捐机构电话" width="120" />
            <el-table-column prop="agencyStartTime" label="募捐机构创办时间" :formatter="handleFormatDate" width="150" />
            <el-table-column prop="agencyWebsite" label="募捐机构网址" width="200" />
            <el-table-column prop="agencyFax" label="募捐机构传真" width="150" />
            <el-table-column prop="agencyIntroduction" label="募捐机构简介" width="200" />
            <el-table-column prop="agencyNature" label="募捐机构性质" width="150" />
            <el-table-column prop="agencyAddress" label="募捐机构地址" width="200" />
            <el-table-column prop="organizationRating" label="组织评级" width="100" />
            <el-table-column prop="corporateName" label="法人姓名" width="100" />
            <el-table-column prop="corporateId" label="法人身份证号" width="170" />
            <el-table-column prop="staffsNumber" label="专职人员人数" width="100" />
            <el-table-column prop="volunteersNumber" label="志愿者人数" width="100" />
            <el-table-column prop="socialCreditCode" label="社会统一信用代码" width="150" />
            <el-table-column prop="registrationAdministrationAuthority" label="登记管理机关" width="150" />
            <el-table-column prop="registrationCertificateType" label="登记证书类型" width="150" />
            <el-table-column prop="registrationCertificatePhoto" label="登记证书照片" width="120">
                <template #default="scope">
                    <el-image :src="imageUrl + scope.row.registrationCertificatePhoto" style="width: 50px; height: 50px" />
                </template>
            </el-table-column>
            <el-table-column prop="registrationCertificateAddress" label="登记证书地址" width="200" :formatter="handleFormatAddress" />
            <el-table-column prop="certificateTimes" label="登记证书有效期" width="200" />
            <el-table-column prop="bussinessScope" label="经营范围" width="200" />
            <el-table-column label="操作" fixed="right" width="110">
                <template #default="{ row }">
                    <el-button link type="primary" @click="handleEdit(0, row)">编辑</el-button>
                    <el-button link type="primary" @click="handleDelete('single', row.agencyId)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="pagination">
            <el-pagination
                background
                layout="total, sizes, prev, pager, next,jumper"
                :page-sizes="[10, 50, 100]"
                :total="total"
                v-model:page-size="pageSize"
                v-model:current-page="currentPage"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
        </div>
        <!-- 编辑募捐机构信息弹窗 -->
        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="80%" :style="{ height: '80%' }">
            <AgencyRegister :dialogForm="dialogForm" />
            <template #footer>
                <el-button type="primary" @click="handleSure">确定</el-button>
                <el-button @click="dialogVisible = false">取消</el-button>
            </template>
        </el-dialog>
    </div>
  </template>
  
<script lang="ts" setup>
import { onMounted, ref } from 'vue';
import { adminApi } from '../../api/app';
import { Plus, Search, Minus } from '@element-plus/icons-vue'
import { imageUrl } from '../../api/request';
  import { dayjs, ElMessage, ElMessageBox, UploadProps } from 'element-plus';
import { handleFormatDate, agencyNatureList, ratingList, registrationCertificateTypeList, handleFormatAddress } from './ts/common';
import AgencyRegister from './AgencyRegister.vue';
  
/** 搜索表单 */
const searchForm = ref({
    agencyId: null,
    agencyName: null,
    agencyPhone: null,
    agencyNature: null,
    organizationRating: [],
    corporateName: null,
    socialCreditCode: null,
    registrationCertificateType: null,
    registrationCertificateAddress: null
})
/** 表格数据 */
const tableData = ref([])
/** 数据总数 */
const total = ref(0);
/** 当前页码 */
const currentPage = ref(1);
/** 每页显示条数 */
const pageSize = ref(10);
  /** 多选选中内容 */
  const selection = ref<any[]>([]);
/** 编辑捐赠者信息弹窗可见性 */
const dialogVisible = ref(false);
/** 编辑 | 新增弹窗标题 */
const dialogTitle = ref('');
/** 编辑 | 新增弹窗表单 */
const dialogForm = ref({
    agencyId: null,
    agencyName: null,
    agencyLogo: null,
    agencyEmail: null,
    agencyPhone: null,
    agencyStartTime: null,
    agencyWebsite: null,
    agencyFax: null,
    agencyIntroduction: null,
    registrationAdministrationAuthority: null,
    registrationCertificateType: null,
    registrationCertificatePhoto: null,
    registrationCertificateAddress: null,
    socialCreditCode: null,
    organizationRating: null,
    agencyNature: null,
    staffsNumber: null,
    volunteersNumber: null,
    corporateName: null,
    corporateId: null,
    bussinessScope: null,
    certificateTimes: null,
    agencyAddress: null,
    agencyPassword: null,
    orgLegalIdCardIsLongTerm: false, // 证书有效期是否长期
    address: [], // 地址
});
  
// 初始加载
onMounted(() => {
    // 获取募捐机构列表
    getAgencyList();
});
  
/** 获取募捐机构信息列表 */
const getAgencyList = () => {
    // 如果选择了组织评级，需要拼接
    let rating: string = '';
    if (Array.isArray(searchForm.value.organizationRating)) {
        rating = searchForm.value.organizationRating.join('/'); // 数组转字符串
    }
    adminApi.getAgencies({ 
        pageNum: currentPage.value, 
        pageSize: pageSize.value, 
        ...searchForm.value,
        organizationRating: rating
    }).then((res: any) => {
        if (res) {
            tableData.value = res.records;
            total.value = res.total;
        }
    });
};
  
/** 多选变化 */
const handleSelectionChange = (val: any) => {
    val.forEach((element: any) => selection.value.push(element.agencyId));
};
  
/** 新增 | 编辑募捐机构信息 */
const handleEdit = (type: number, row?: any) => {
    dialogTitle.value = '新增募捐机构信息';
    resetForm();
    // 编辑模式 需要给表单赋值当前行数据
    if (type === 0) {
        dialogTitle.value = '编辑募捐机构信息';
        // 登记证书地址拆分
        const allAddress = row.registrationCertificateAddress.split('/') || [];
        const address = allAddress.splice(0, 3); // 省市区
        // 登记有效期拆分
        const certificateTimes = row.certificateTimes.split('~');
        const orgLegalIdCardIsLongTerm = !(certificateTimes.length > 1);
        dialogForm.value = { 
            ...row,
            organizationRating: row.organizationRating.split('/'), // 字符串转数组
            certificateTimes: orgLegalIdCardIsLongTerm ? new Date(certificateTimes[0]) : [new Date(certificateTimes[0]), new Date(certificateTimes[1])], // 字符串转时间戳数组
            orgLegalIdCardIsLongTerm: orgLegalIdCardIsLongTerm,
            address: address,
            registrationCertificateAddress: allAddress.toString(), // 数组转字符串
            agencyStartTime: new Date(row.agencyStartTime) // 字符串转时间戳
        };
    };
    dialogVisible.value = true;
}
  
/** 重置内容 */
const resetForm = () => {
    dialogForm.value = {
        agencyId: null,
        agencyName: null,
        agencyLogo: null,
        agencyEmail: null,
        agencyPhone: null,
        agencyStartTime: null,
        agencyWebsite: null,
        agencyFax: null,
        agencyIntroduction: null,
        registrationAdministrationAuthority: null,
        registrationCertificateType: null,
        registrationCertificatePhoto: null,
        registrationCertificateAddress: null,
        socialCreditCode: null,
        organizationRating: null,
        agencyNature: null,
        staffsNumber: null,
        volunteersNumber: null,
        corporateName: null,
        corporateId: null,
        bussinessScope: null,
        certificateTimes: null,
        agencyAddress: null,
        agencyPassword: null,
        orgLegalIdCardIsLongTerm: false,
        address: [],
    };
}
  
/** 重置弹窗内容并关闭弹窗 */
const resetDialog = () => {
    resetForm();
    dialogVisible.value = false;
    getAgencyList();
};
  
/** 弹窗确定 */
const handleSure = () => {
    // 处理地址存储格式
    const registrationCertificateAddress = dialogForm.value.address.join('/') + '/' + dialogForm.value.registrationCertificateAddress;
    // 处理时间格式
    let certificateTimes: string;
    // 长期有效，直接转换，短期有效，拼接
    if (dialogForm.value.orgLegalIdCardIsLongTerm) {
        certificateTimes = dayjs(dialogForm.value.certificateTimes).format('YYYY-MM-DD');
    } else {
        certificateTimes = dayjs(dialogForm.value.certificateTimes?.[0]).format('YYYY-MM-DD') + '~' + dayjs(dialogForm.value.certificateTimes?.[1]).format('YYYY-MM-DD');
    }
    const agency = {
        ...dialogForm.value,
        address: null,
        registrationCertificateAddress: registrationCertificateAddress,
        orgLegalIdCardIsLongTerm: undefined,
        certificateTimes: certificateTimes,
        organizationRating: (dialogForm.value.organizationRating || []).join('/'),
        agencyStartTime: dayjs(dialogForm.value.agencyStartTime).format('YYYY-MM-DD')
    }
    if (dialogTitle.value === '新增募捐机构信息') {
        adminApi.addAgency(agency).then(res => {
            if (res) {
                ElMessage.success('新增成功');
                resetDialog();
            }
        }).catch(() => {
            ElMessage.error('新增失败');
        });
    } else {
        adminApi.updateAgency(agency).then(res => {
            if (res) {
                ElMessage.success('编辑成功');
                resetDialog();
            }
        }).catch(() => {
            ElMessage.error('编辑失败');
        });
    }
};

/** 删除募捐机构 */
const handleDelete = (control: string, agencyId?: string) => {
    ElMessageBox.confirm('确定删除吗？', '注意', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        const agencyIds = control === 'single' ? [agencyId] : selection.value;
        adminApi.deleteAgencies(agencyIds).then(res => {
            if (res) {
                ElMessage.success('删除成功');
                getAgencyList();
                // 批量删除清空选中内容
                if (control === 'batch') {
                    selection.value = [];
                }
            } else {
                ElMessage.error('删除失败');
            }
        });
    }).catch(() => {
        ElMessage.info('已取消');
    });
}
  
/** 表格分页大小改变 */
const handleSizeChange = (val: number) => {
    pageSize.value = val;
    getAgencyList();
};
  
/** 表格页码改变 */
const handleCurrentChange = (val: number) => {
    currentPage.value = val;
    getAgencyList();
};
</script>
  
  <style lang="less">
  @import "./css/tableForm.less";
  .el-dialog__body {
    height: 80%;
  }
  </style>